<?php
require_once 'CMS/Util.php';
require_once 'CMS/Mvc/BaseController.php';
require_once 'CMS/Mvc/BaseUserController.php';
require_once 'CMS/UserCommon.php';
include "CMS/class.phpmailer.php"; 
include "CMS/class.smtp.php"; 
include "CMS/class.pop3.php";
require_once 'CMS/User.php';
require_once 'CMS/Language.php'; //include thu vien language

//Người tạo : Hồ Nhật Tân - Team 1
//Module 	: Register
//Chức năng	: Đăng ký tài khoản người dùng
 
class RegisterController extends BaseUserController{

	public function init(){
		parent::init();
		$tbSetting = new User_Model_Parameter();
		$temp = $tbSetting->selectSetting("config");
		$layout = unserialize($temp[0]["parameter_value"]);
		if($layout['config_template'] !="")
		{
			$this->_helper->layout()->setLayout($layout['config_template']);
			$_SESSION['config_template'] = $layout['config_template'];
		}
		else
		{
			$this->_helper->layout()->setLayout('layoutmain');
			$_SESSION['config_template'] = 'layoutmain';
		}
	}

//Action index thực hiện chức năng xử lý dữ liệu đăng ký
    public function indexAction(){
    	$_SESSION['page_code'] = 'register';
		
		$tbSidebarModule = new User_Model_SidebarModule();
		$Modules = $tbSidebarModule->selectAllModule();
		foreach($Modules as $module)
		{
			$database_show_widget [] = $module["module_code"];
			$database_order_widget [$module["module_code"]] =  $module["sort_order"];
		}
		
		$tbDefaultbarModule = new User_Model_DefaultModuleToPage();
		$defaultModules = $tbDefaultbarModule->selectAllModule("register");
		if($defaultModules!=null) {
		foreach($defaultModules as $dmodule)
		{
			$content_show_widget [] = $dmodule["module_code"];
			$content_order_widget [$dmodule["module_code"]] =  $dmodule["sort_order"];
		} }
		
		$tbContentbarModule = new User_Model_ContentModuleToPage();
		// mac dinh homepage
		$ContentModules = $tbContentbarModule->selectAllModule("register");
		if($ContentModules!=null) {	
		foreach($ContentModules as $cmodule)
		{
			$content_show_widget [] = $cmodule["module_code"];
			$content_order_widget [$cmodule["module_code"]] =  $cmodule["sort_order"];
		}	}
		
		$front     = Zend_Controller_Front::getInstance();
		$widgets = $front->getPlugins();
	
		foreach($widgets as $widget)
		{
			if(count($Modules) > 0){
				if($widget->name !="" && in_array($widget->name, $database_show_widget))
				{
					$widget->enable = 1;
					$widget->order = $database_order_widget[$widget->name];
				}
			}
			if(count($content_show_widget) > 0){
				if($widget->name !="" && in_array($widget->name, $content_show_widget))
				{
						$widget->enable = 1;
						$widget->order = $content_order_widget[$widget->name];
				}		
			}
		}
		
		
    	//Start------Check Input Parameter
    	
		//End--------Check Input Parameter
		
		//Start------Khai báo các parameter
		$dbUser = new User_Model_Users();
		$dateInt = new Util();
		//End--------Khai báo các parameter
		
		//Start------Kiểm tra có tài khoản đăng nhập chưa
    	$session = new Zend_Session_Namespace('login.auth');
		if(isset($session->id_user))
		{
			$this->_redirect('index/index');
		}
		//End--------Kiểm tra có tài khoản đăng nhập chưa
		
		/*========== Start Load Language ==========*/
			$language = new Language(APPLICATION_PATH . '/modules/user/languages/register');
			if(isset($_SESSION['language']))
			{
				$language_id = $_SESSION['language'];
				$tbLanguage = new Language_Model_Language();
				$name = $tbLanguage->getNameLanguage($language_id);
				$language->load($name['name']);
			}
			else
				$language->load('Default');		
				
			$languages = $tbLanguage->getAllLanguages();
			$this->view->languages = $languages;
		/*========== End Load Language ==========*/
				
		/*========== Start Get Text ==============*/
			$this->view->text_title_register 	= $language->get('text_title_register');
			$this->view->text_tip 				= $language->get('text_tip');
			$this->view->text_title_mail 		= $language->get('text_title_mail');
			
			$this->view->text_lguser 			= $language->get('text_lguser');
			$this->view->text_username 			= $language->get('text_username');
			$this->view->text_pass 				= $language->get('text_pass');
			$this->view->text_confirmpass 		= $language->get('text_confirmpass');
			
			$this->view->text_lgprofile 		= $language->get('text_lgprofile');
			$this->view->text_name 				= $language->get('text_name');
			$this->view->text_email 			= $language->get('text_email');
			$this->view->text_comfirmemail 		= $language->get('text_comfirmemail');
			$this->view->text_sex 				= $language->get('text_sex');
			$this->view->text_birthday 			= $language->get('text_birthday');
			$this->view->text_address 			= $language->get('text_address');
			$this->view->text_career 			= $language->get('text_career');
			
			$this->view->text_lgcaptcha 		= $language->get('text_lgcaptcha');
			$this->view->text_captcha 			= $language->get('text_captcha');
			$this->view->text_inputcaptcha 		= $language->get('text_inputcaptcha');
			
			$this->view->text_submit 			= $language->get('text_submit');
			$this->view->text_cancel 			= $language->get('text_cancel');
			
			$this->view->text_sex1 				= $language->get('text_sex1');
			$this->view->text_sex0 				= $language->get('text_sex0');
			$this->view->text_day 				= $language->get('text_day');
			$this->view->text_month 			= $language->get('text_month');
			$this->view->text_year 				= $language->get('text_year');
			$this->view->text_select 			= $language->get('text_select');
			
			$this->view->error_pass1 		= $language->get('error_pass1');
			$this->view->error_pass2 		= $language->get('error_pass2');
			$this->view->error_pass3 		= $language->get('error_pass3');
			$this->view->error_pass4 		= $language->get('error_pass4');
			$this->view->error_pass5 		= $language->get('error_pass5');
			$this->view->error_pass6 		= $language->get('error_pass6');
			
			$this->view->error_profile1 	= $language->get('error_profile1');
			$this->view->error_profile2 	= $language->get('error_profile2');
			$this->view->error_profile3 	= $language->get('error_profile3');
			$this->view->error_profile4 	= $language->get('error_profile4');
			$this->view->error_profile5 	= $language->get('error_profile5');
			$this->view->error_profile6 	= $language->get('error_profile6');
			$this->view->error_profile7 	= $language->get('error_profile7');
			$this->view->error_profile8 	= $language->get('error_profile8');
			
			$this->view->error_account1 	= $language->get('error_account1');
			$this->view->error_account2 	= $language->get('error_account2');
			$this->view->error_validuser1 	= $language->get('error_validuser1');
			$this->view->error_validuser2 	= $language->get('error_validuser2');
			$this->view->error_validuser3 	= $language->get('error_validuser3');
		/*========== End Text ==============*/
		
		//Start------Khởi tạo mã captcha
	    $captcha = new Zend_Captcha_Image();
		$captcha	->setTimeout('300')
	                ->setWordLen('6')
	                ->setHeight('50')
	                ->setWidth('160')
	                ->setImgDir(APPLICATION_PATH . '/../public/captcha/images/')
	                ->setImgUrl('/captcha/images/')
	                ->setSuffix('.jpg')
	                ->setFont(APPLICATION_PATH . '/../public/captcha/font/jkasperville.ttf')
	                ->setFontSize('30')
	                ->setLineNoiseLevel('5')
	            	->setDotNoiseLevel('50')
	            	->setExpiration('1')
	           	 	->setGcFreq('1');
		$captcha->generate();
		$this->view->captcha = $captcha->render($this->view); 
		$this->view->captchaID = $captcha->getId();
		//End--------Khởi tạo mã captcha
		
		//Start------Đưa chuỗi captcha vào session
		$captchaSession = new Zend_Session_Namespace('Zend_Captcha_' . $captcha->getId());
		$captchaSession->word = $captcha->getWord();
		//End--------Đưa chuỗi captcha vào session
		
		//Start------Kiểm tồn tại username trong database
   		if(count($_GET) && isset($_GET["username"]))
		{
			$checkuser = $_GET['username'];
			
			//Start------Get User
			$datauser = $dbUser->getUser($checkuser);
			//End--------Get User xmlhttp.readyState
			
	        if(isset($datauser[0])){
	        	$success = 0;
			}
			else{
				$success = 1;
			}
			$this->_helper->json($success);
		}
		//End--------Kiểm tồn tại username trong database
		
		//Start------Đổi catcha mới
    	if(count($_GET) && isset($_GET["captcha"]))
		{
			//Start------Tạo mã captcha mới
			$captchaNew = $captcha->render($this->view); 
			$captchaID = $captcha->getId();
			//End--------Tạo mã captcha mới
			
			//Start------Đưa chuỗi captcha vào session
			$captchaSession = new Zend_Session_Namespace('Zend_Captcha_' . $captcha->getId());
			$captchaSession->word = $captcha->getWord();
			//End--------Đưa chuỗi captcha vào session
			
			$this->_helper->json($captchaID);
		}
		//End--------Đổi catcha mới
		
		//Start------Xử lý đăng ký tài khoản
		if ($this->_request->isPost()){
			
			//Start------Lấy dữ liệu từ form đăng ký
	        $flag=true;
	        $username = $this->_request->getParam('txtUsername');
	        $password = $this->_request->getParam('txtPassword');
	        $fullname = $this->_request->getParam('txtFullName');
	        $sex = $this->_request->getParam('sltSex');
	        $dbirthday = $this->_request->getParam('dBirthday');
	        $mbirthday = $this->_request->getParam('mBirthday');
	        $ybirthday = $this->_request->getParam('yBirthday');
	        //$birthday = $ybirthday . "." . $mbirthday . "." . $dbirthday;
	        //$now = time()+7*3600;
	        $now = $dateInt->get_time_now();
	        $birthday = $dateInt->change_date_to_int($mbirthday, $dbirthday, $ybirthday);
	        //$now=getdate();
	        //$datenow = $now["year"] . "." . $now["mon"] . "." . $now["mday"];
	        $email = $this->_request->getParam('txtEmail');
	        $address = $this->_request->getParam('txtAddress');
	        $career = $this->_request->getParam('txtCareer');
	        $txtCaptcha = $this->_request->getParam('txtCaptcha');
			$captchaID = $this->_request->getParam('hdnCaptcha');
	        //End--------Lấy dữ liệu từ form đăng ký
	        
			//Start------Trả dữ liệu đã nhập về form
			$this->view->username = $username;
			$this->view->fullname = $fullname;
			$this->view->email = $email;
			$this->view->sex = $sex;
			$this->view->dbirthday = $dbirthday;
			$this->view->mbirthday = $mbirthday;
			$this->view->ybirthday = $ybirthday;
			$this->view->address = $address;
			$this->view->career = $career;
			//End--------Trả dữ liệu đã nhập về form
			
	        //Start------Get User
			$datauser = $dbUser->getUser($username);
			//End--------Get User
			
			//Start------Get Email
			$dataemail = $dbUser->getEmail($email);
			//End--------Get Email
			
			//Start------Kiểm tra username nhập từ form
	        
			if(isset($datauser[0])){
	        	$flag = false;
	        	$this->view->userError = $username;
			}
			//End--------Kiểm tra username nhập từ form
			
			//Start------Kiểm tra email nhập từ form
			if(isset($dataemail[0])){
				$flag = false;
				$this->view->emailError = $email;
			}
			//End--------Kiểm tra email nhập từ form
			
			//Start------Lấy thông tin captcha từ session
         	$captchaSession = new Zend_Session_Namespace('Zend_Form_Captcha_' . $captchaID);
         	$captchaIterator = $captchaSession->getIterator();
         	$captchaWord = $captchaIterator['word'];
         	//End--------Lấy thông tin captcha từ session
         	
         	//Start------Kiểm tra captcha nhập từ form
			if(strtolower($txtCaptcha) != strtolower($captchaWord)){
				$flag = false;
				$this->view->captchaError = $txtCaptcha;
			}
			//End--------Kiểm tra captcha nhập từ form
			
			//Start------Lưu dữ liệu đăng ký vào database
			$data=array(
				'user_name' 	=> $username,
				'user_code' 	=> $username,
				'password' 		=> md5($password),
				'full_name' 	=> $fullname,
				'sex' 			=> $sex,
				'birth_day' 	=> $birthday,
				'email' 		=> $email,
				'address' 		=> $address,
				'career' 		=> $career,
				'avatar'		=> "/data/noavatar.gif",
				'created_date' 	=> $now,
				'updated_date' 	=> $now,
				'group_id' 	=> 1,
				'status' 	=> 1,
			
			);
			
			if($flag == true){
				
				//Start------Insert User
				$result = $dbUser->insertUser($data);
				//End--------Insert User
				
				//Start------Thông báo đăng ký thành công hoặc thất bại
				if($result == -1){
					$this->_redirect('register/success?error');
				}
				else{
					//Start------select UserInfo
					$user = $dbUser->selectUserInfo($username);
					//End--------select UserInfo
					$session = new Zend_Session_Namespace('login.auth');
					//Start------Lưu session
					$session->id_user = $user['user_id'];
					$session->name_user = $user['user_name'];
					//End--------Lưu session
					
					$this->_redirect('register/success');
				}
				//End--------Thông báo đăng ký thành công hoặc thất bại
			}
			//End--------Lưu dữ liệu đăng ký vào database
		}
		//End--------Xử lý đăng ký tài khoản
	}
	
//action email
	public function emailAction() 
	{
		$_SESSION['page_code'] = 'register';
		
		$tbSidebarModule = new User_Model_SidebarModule();
		$Modules = $tbSidebarModule->selectAllModule();
		foreach($Modules as $module)
		{
			$database_show_widget [] = $module["module_code"];
			$database_order_widget [$module["module_code"]] =  $module["sort_order"];
		}
		
		$tbDefaultbarModule = new User_Model_DefaultModuleToPage();
		$defaultModules = $tbDefaultbarModule->selectAllModule("register");
		if($defaultModules!=null) {
		foreach($defaultModules as $dmodule)
		{
			$content_show_widget [] = $dmodule["module_code"];
			$content_order_widget [$dmodule["module_code"]] =  $dmodule["sort_order"];
		} }
		
		$tbContentbarModule = new User_Model_ContentModuleToPage();
		// mac dinh homepage
		$ContentModules = $tbContentbarModule->selectAllModule("register");
		if($ContentModules!=null) {
		foreach($ContentModules as $cmodule)
		{
			$content_show_widget [] = $cmodule["module_code"];
			$content_order_widget [$cmodule["module_code"]] =  $cmodule["sort_order"];
		}	}
		
		$front     = Zend_Controller_Front::getInstance();
		$widgets = $front->getPlugins();
	
		foreach($widgets as $widget)
		{
			if(count($Modules) > 0){
				if($widget->name !="" && in_array($widget->name, $database_show_widget))
				{
					$widget->enable = 1;
					$widget->order = $database_order_widget[$widget->name];
				}
			}
			if(count($content_show_widget) > 0){
				if($widget->name !="" && in_array($widget->name, $content_show_widget))
				{
						$widget->enable = 1;
						$widget->order = $content_order_widget[$widget->name];
				}		
			}
		}
		
		/*========== Start Load Language ==========*/
			$language = new Language(APPLICATION_PATH . '/modules/user/languages/register');
			if(isset($_SESSION['language']))
			{
				$language_id = $_SESSION['language'];
				$tbLanguage = new Language_Model_Language();
				$name = $tbLanguage->getNameLanguage($language_id);
				$language->load($name['name']);
			}
			else
				$language->load('Default');		
				
			$languages = $tbLanguage->getAllLanguages();
			$this->view->languages = $languages;
		/*========== End Load Language ==========*/
				
		/*========== Start Get Text ==============*/
			$this->view->text_title_mail 	= $language->get('text_title_mail');
			$this->view->text_username 		= $language->get('text_username');
			$this->view->text_send 			= $language->get('text_send');
			
			$this->view->error_mail1 		= $language->get('error_mail1');
			$this->view->error_mail2 		= $language->get('error_mail2');
			$this->view->error_mail3 		= $language->get('error_mail3');
			$this->view->error_mail4 		= $language->get('error_mail4');
			$this->view->text_tip 			= $language->get('text_tip');
		/*========== End Text ==============*/
		
		$ForgotPWMessage = "";
		if(isset($_POST["userID"]) && trim($_POST["userID"])!='')
		{
			$username=$_POST["userID"];

			$tbUser = new User_Model_Users();
			$dateInt = new Util();
			try{	
				//Start-----------Lấy thông tin user
				$userInfo = $tbUser->selectUserInfo($username);
				$user_id = $userInfo[user_id];
				//End-------------Lấy thông tin
				
				if($user_id!="")
				{
					//Star-------Tạo password ngẫu nhiên và lấy ngày sửa
					$newpw = $this->generatePassword();
					$now = $dateInt->get_time_now();
					$data=array(
						'password' 		=> md5($newpw),
						'updated_date' 	=> $now
					);
					//End--------Tạo password ngẫu nhiên và lấy ngày sửa
					
					//Start------Đổi mật khẩu
					$result = $tbUser->updateAccount($user_id, $data);
					//End--------Đổi mật khẩu
						
					//Start------Thông báo đăng ký thành công hoặc thất bại
					if($result == -1){
						$ForgotPWMessage= "Can't access";
					}
					else{
						//Start------Đổi thành công thì gửi thư thông báo
						if($userInfo[email])
						{
							$fromName = 'Administrator';
							$mail = new PHPMailer();
							$mail->IsSMTP(); // set mailer to use SMTP
							$mail->Host = "smtp.gmail.com"; // specify main and backup server
							$mail->Port = 465; // set the port to use
							$mail->SMTPAuth = true; // turn on SMTP authentication
							$mail->SMTPSecure = 'ssl';
							$mail->Username = "aibietdau111@gmail.com"; // your SMTP username or your gmail username
							$mail->Password = "naythipass"; // your SMTP password or your gmail password
							$from 	= "aibietdau111@gmail.com"; // Reply to this email
							$to 	= $userInfo[email]; // Recipients email ID
							$toName = $userInfo[full_name]; // Recipient's name
							$message= "Hello,<br/>
										You have assigned to recovery your password. Please use these information to log in your acccount: <br/>
										Your username: $username.<br/>
										Your password: $newpw<br/><br/>
										Best regards,<br/>
										$fromName";
							$mail->From = $from;
							$mail->FromName = $fromName; // Name to indicate where the email came from when the recepient received
							$mail->AddAddress($to,$toName);
							$mail->AddReplyTo($from,$fromName);
							$mail->WordWrap = 50; // set word wrap
							$mail->IsHTML(true); // send as HTML
							$mail->Subject = "This is the recovery mail for your account";
							$mail->Body = $message;
							//$mail->SMTPDebug = 2;
							if(!$mail->Send())
							{
								$ForgotPWMessage = $language->get('error_mail1');
								$this->_redirect('register/success?action=1');
							}
							else
							{
								$ForgotPWMessage= $language->get('error_mail2');
								$this->_redirect('register/success?action=1');
							}
						}
						else
						{
							$ForgotPWMessage = $language->get('error_mail1');
						}
						//End--------Gửi thư			
					}
				}
				else
				{
					$ForgotPWMessage= $language->get('error_mail3');
				}
			}
			catch (Exception $e)
			{ 
				$ForgotPWMessage = "";
			}
		}
		else if(isset($_POST["userID"]))
		{
			$ForgotPWMessage = $language->get('error_mail4');
		}
        $this->view->ForgotPWMessage = $ForgotPWMessage;
	}
	
	//Hàm tạo password ngẫu nhiên
	function generatePassword() 
	{
		$length=9;
		$big = 'QWERTYUIOPLKJHGFDSAZXCVBNM';
		$small = 'qwertyuuioplkjhgfdsazxcvbnm';
		$small .= '123456789';
		$small .= '@#$%^&*!~';
	 
		$password = '';
		$alt = time() % 2;
		for ($i = 0; $i < $length; $i++) {
			if ($alt == 1) {
				$password .= $small[(rand() % strlen($small))];
				$alt = 0;
			} else {
				$password .= $big[(rand() % strlen($big))];
				$alt = 1;
			}
		}
		return $password;
	}

//Action success thực hiện chức năng xuất thông báo đăng ký tài khoản thành công hoặc thất bại
	public function successAction(){
	$_SESSION['page_code'] = 'success';
		
		$tbSidebarModule = new User_Model_SidebarModule();
		$Modules = $tbSidebarModule->selectAllModule();
		foreach($Modules as $module)
		{
			$database_show_widget [] = $module["module_code"];
			$database_order_widget [$module["module_code"]] =  $module["sort_order"];
		}
		
		$tbDefaultbarModule = new User_Model_DefaultModuleToPage();
		$defaultModules = $tbDefaultbarModule->selectAllModule("success");
		if($defaultModules!=null) {
		foreach($defaultModules as $dmodule)
		{
			$content_show_widget [] = $dmodule["module_code"];
			$content_order_widget [$dmodule["module_code"]] =  $dmodule["sort_order"];
		} }
		
		$tbContentbarModule = new User_Model_ContentModuleToPage();
		// mac dinh homepage
		$ContentModules = $tbContentbarModule->selectAllModule("success");
		if($ContentModules!=null) {
		foreach($ContentModules as $cmodule)
		{
			$content_show_widget [] = $cmodule["module_code"];
			$content_order_widget [$cmodule["module_code"]] =  $cmodule["sort_order"];
		}	}
		
		$front     = Zend_Controller_Front::getInstance();
		$widgets = $front->getPlugins();
	
		foreach($widgets as $widget)
		{
			if(count($Modules) > 0){
				if($widget->name !="" && in_array($widget->name, $database_show_widget))
				{
					$widget->enable = 1;
					$widget->order = $database_order_widget[$widget->name];
				}
			}
			if(count($content_show_widget) > 0){
				if($widget->name !="" && in_array($widget->name, $content_show_widget))
				{
						$widget->enable = 1;
						$widget->order = $content_order_widget[$widget->name];
				}		
			}
		}
		
		/*========== Start Load Language ==========*/
			$language = new Language(APPLICATION_PATH . '/modules/user/languages/register');
			if(isset($_SESSION['language']))
			{
				$language_id = $_SESSION['language'];
				$tbLanguage = new Language_Model_Language();
				$name = $tbLanguage->getNameLanguage($language_id);
				$language->load($name['name']);
			}
			else
				$language->load('Default');		
				
			$languages = $tbLanguage->getAllLanguages();
			$this->view->languages = $languages;
		/*========== End Load Language ==========*/
				
		/*========== Start Get Text ==============*/
			$this->view->text_success1 		= $language->get('text_success1');
			$this->view->text_success2 		= $language->get('text_success2');
			$this->view->text_success3 		= $language->get('text_success3');
			$this->view->text_success4 		= $language->get('text_success4');
			$this->view->text_success5 		= $language->get('text_success5');
			$this->view->text_success6 		= $language->get('text_success6');
			$this->view->text_success7 		= $language->get('text_success7');
		/*========== End Text ==============*/
	}
	
}